import React,{useState,useEffect,useContext,useRef, useReducer} from "react";
import * as echarts from 'echarts';
import './style.css';
import { barContext } from "../../contexts";
// todo 放到 store 中
import {initialOption} from '../../options/index';

import {getData} from '../../util';


export default function EchartsBar(props) {    
    const {state:{maxvalue,minvalue,numvalue,orderValue}} = useContext(barContext);

    let chartDom = useRef(null),
        chartInstance = null;

    const render = function() {
        
        const myChart = echarts.getInstanceByDom(chartDom.current);
        let {keys,values} = getData(minvalue,maxvalue,numvalue,orderValue);

        if(myChart) {
            chartInstance = myChart;
        }else {
            chartInstance = echarts.init(chartDom.current)
        }
        
        chartInstance.setOption({
            ...initialOption,
            xAxis: {
                type: 'category',
                data: keys
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  data: values,
                  type: 'bar',
                  itemStyle: {        //上方显示数值
                    normal: {
                        label: {
                            show: true, //开启显示
                            position: 'top', //在上方显示
                            textStyle: { //数值样式
                                color: 'black',
                                fontSize: 16
                            }
                        }
                    }
                }
                }
                
            ]

        });
        
    }
    
    useEffect(() => {

        
        render();

      },[maxvalue,minvalue,numvalue,orderValue])

      

    return (
        <div>
            
            <div className="bar-chart" ref={chartDom}></div>
        </div>
         
    )
}